package com.lindroy.androidplayer.ui.project

import android.os.Bundle
import android.view.View
import com.lindroy.androidplayer.base.BaseListFragment
import com.lindroy.androidplayer.databinding.FragmentProjectListBinding
import com.lindroy.androidplayer.ui.adapter.ProjectAdapter
import com.lindroy.androidplayer.ui.webview.WebViewFragment
import com.lindroy.androidplayer.utils.addSimpleDivider
import com.lindroy.androidplayer.utils.collectListWhenResumed
import com.lindroy.androidplayer.utils.orFalse
import com.lindroy.androidplayer.utils.orZero
import com.lindroy.androidplayer.viewmodels.ProjectViewModel

/**
 * @author Lin
 * @date 2022/1/19
 * @function
 */
class
ProjectListFragment : BaseListFragment<FragmentProjectListBinding, ProjectViewModel>() {

    private val typeId by lazy { arguments?.getInt(KEY_PROJECT_ID).orZero() }

    private val adapter by lazy { ProjectAdapter(viewLifecycleOwner) }

    override fun FragmentProjectListBinding.initView(savedInstanceState: Bundle?) {
        vm = mViewMode
        rvProject.adapter = adapter.withFooter()
        rvProject.addSimpleDivider()
    }

    override fun FragmentProjectListBinding.initListener() {
        mViewMode.setLayoutStateFlow(adapter.loadStateFlow)
        mViewMode.getProjectList(typeId).collectListWhenResumed(viewLifecycleOwner) {
            adapter.submitData(it)
        }
        mViewMode.itemClickAction.observe(viewLifecycleOwner){
            WebViewFragment.start(this@ProjectListFragment,it.id,it.url,it.title,it.collected.value.orFalse())
        }
    }

    companion object {
        private const val KEY_PROJECT_ID = "id"
        fun create(id: Int) = ProjectListFragment().apply {
            arguments = Bundle().apply {
                putInt(KEY_PROJECT_ID, id)
            }
        }
    }

    override fun onRefresh() {
        adapter.refresh()
    }

    override fun onRetry(view: View) {
        adapter.refresh()
    }
}